C++ Map 中的 operator[]函数

首页 / C++入门教程 / C++ Map 中的 operator[]函数

C ++映射 operator [] strong>函数用于通过给定的键值 strong>访问映射中的元素。

它类似于 at() strong>函数。它们之间的唯一区别是,如果映射中不存在所访问的密钥,则抛出异常;反之,如果密钥中不存在该密钥,则 operator [] strong>会将密钥插入映射中。地图。

句法

考虑键值 k strong>,语法为:

mapped_type& operator[] (const key_type& k);    //until C++ 11
mapped_type& operator[] (const key_type& k);   //since C++ 11
mapped_type& operator[] (key_type&& k); //since C++ 11

范围

k strong>:访问其映射值的元素的键值。

返回值

它使用键值返回对元素映射值的引用。

例子1

让我们看一个访问元素的简单示例。

#include <iostream>
#include <map>
using namespace std;
int main() 
{
  
   map<char, int> m = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5},
            };

   cout << "Map contains following elements" << endl;

   cout << "m['a'] = " << m['a'] << endl;
   cout << "m['b'] = " << m['b'] << endl;
   cout << "m['c'] = " << m['c'] << endl;
   cout << "m['d'] = " << m['d'] << endl;
   cout << "m['e'] = " << m['e'] << endl;

   return 0;
}

输出 strong>:

Map contains following elements
m['a'] = 1
m['b'] = 2
m['c'] = 3
m['d'] = 4
m['e'] = 5

在上面,operator []函数用于访问map的元素。

例子2

让我们看一个简单的示例,使用它们的键值添加元素。

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main ()
{
  map<int,string> mymap = {
                { 101, "" },
                { 102, "" },
                { 103, ""} };

  mymap[101] = "Java"; 
  mymap[102] = "T";
  mymap[103] = "Point";


		// prints value associated with key 101, i.e. Java
  cout<<mymap[101]; 
          // prints value associated with key 102, i.e T
  cout<<mymap[102];
          // prints value associated with key 103, i.e Point	
  cout<<mymap[103];

  return 0;
}

输出 strong>:

JavaTPoint 

在上面的示例中,operator []用于在初始化后使用关联的键值添加元素。

例子3

让我们看一个简单的示例,以更改与键值关联的值。

无涯教程网

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main ()
{
  map<int,string> mymap = {
                { 100, "Nikita"},
                { 200, "Deep"  },
                { 300, "Priya" },
                { 400, "Suman" },
                { 500, "Aman"  }};
                
  cout<<"Elements are:" <<endl;
  for (auto& x: mymap) {
    	cout << x.first << ": " << x.second << '\n';
  }


  mymap[100] = "Nidhi"; // changes the value associated with key 100 to Nidhi
  mymap[300] = "Pinku"; // changes the value associated with key 300 to Pinku
  mymap[500] = "Arohi"; // changes the value associated with key 500 to Arohi
  
  
  cout<<"\nElements after make changes are:" <<endl;
  for (auto& x: mymap) {
    	cout << x.first << ": " << x.second << '\n';
  }
  
  return 0;
}

输出 strong>:

Elements are:
100: Nikita
200: Deep
300: Priya
400: Suman
500: Aman

Elements after make changes are:
100: Nidhi
200: Deep
300: Pinku
400: Suman
500: Arohi

在上面的示例中,operator []函数用于更改与其键值关联的值。

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-map-operator[]-function.html

来源:LearnFk无涯教程网

例子4

让我们看一个简单的例子来区分operator []和at()。

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main ()
{
  map<char,string> mp = {
                { 'a',"Java"},
                { 'b', "C++"  },
                { 'c', "Python" }};
            
    cout<<endl<<mp['a'];
    cout<<endl<<mp['b'];
    cout<<endl<<mp['c'];
    
     mp['d'] = "SQL";   
  /* since there is no key with value 'd' in the map, 
        it insert a key-value pair in map with key 'd' and value = "SQL" */
        
     cout<<endl<<mp['d'];
     
    try {
        mp.at('z'); 
          // since there is no key with value z in the map, it throws an exception 
         
        
    } catch(const out_of_range &e) {
        cout<<endl<<"\nOut of Range Exception at "<<e.what();
    }
return 0;
}

输出 strong>:

Java
C++
Python
SQL

Out of Range Exception at map::at

在上面的示例中,当我们使用at()函数时,由于在映射中不存在带有值z的键,并且当我们使用operator []并在键值d中添加元素时,由于没有键,它会引发out_of_range异常在地图中值为" d"时,它将在地图中插入具有键" d"和值为" SQL"的键-值对。




祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

推荐系统三十六式 -〔刑无刀〕

软件测试52讲 -〔茹炳晟〕

编辑训练营 -〔总编室〕

Django快速开发实战 -〔吕召刚〕

跟着高手学复盘 -〔张鹏〕

Spark性能调优实战 -〔吴磊〕

程序员的测试课 -〔郑晔〕

零基础入门Spark -〔吴磊〕

云时代的JVM原理与实战 -〔康杨〕

好记忆不如烂笔头。留下您的足迹吧 :)